const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const config = require('../config/database');

const basename = path.basename(__filename);
const db = {};

// 创建Sequelize实例
const sequelize = new Sequelize(
  config.development.database,
  config.development.username,
  config.development.password,
  {
    host: config.development.host,
    dialect: config.development.dialect,
    logging: config.development.logging,
    timezone: config.development.timezone
  }
);

// 加载所有模型文件
fs.readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      !file.includes('.test.js')
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

// 设置模型关联
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.User.hasMany(db.Subscription, { foreignKey: 'userId' });
db.Subscription.belongsTo(db.User, { foreignKey: 'userId' });

db.User.hasMany(db.PushRecord, { foreignKey: 'userId' });
db.PushRecord.belongsTo(db.User, { foreignKey: 'userId' });

db.Subscription.hasMany(db.PushRecord, { foreignKey: 'subscriptionId' });
db.PushRecord.belongsTo(db.Subscription, { foreignKey: 'subscriptionId' });

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;